﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using FIFP.DashBoard.Views;
using System.Windows.Browser;
using FIFP.DashBoard.Helper;

namespace FIFP.DashBoard
{
    public partial class App : Application
    {        
        #region Variables
        private static string _customPageName = string.Empty;
        private static string _loginUserId = string.Empty;
        private static string _loginUserName = string.Empty;
        private static string _loginEmail = string.Empty;
        #endregion

        #region Properties
        public enum NavType { NoDefined = 0, Import = 1, Optimization= 2, Scenario= 3 };
        public static string CustomPageName
        {
            get
            {
                return _customPageName;
            }
            set { _customPageName = value; }
        }
        public static string LoginUserId
        {
            get { return _loginUserId; }
            set { _loginUserId = value; }
        }
        public static string LoginUserName
        {
            get { return _loginUserName; }
            set { _loginUserName = value; }
        }       
        public static string LoginEmail
        {
            get { return _loginEmail; }
            set { _loginEmail = value; }
        }
        #endregion

        #region Constructor
        public App()
        {
            this.Startup += this.Application_Startup;
            this.Exit += this.Application_Exit;
            this.UnhandledException += this.Application_UnhandledException;

            InitializeComponent();
        }
        #endregion

        #region NavigationCheck
        private NavType NavigationCheck()
        {
            var url = new Uri(HtmlPage.Window.Eval("window.parent.location.href").ToString());
            var query = url.Query.ToLower();
            if (query.Length == 0)
            {
                
            }
            else
            {
                query = query.Remove(0, 1);
                string[] strings = query.Split('&');
                var parameters = strings.Select(s => s.Split('=')).ToDictionary(item => item[0], temp => temp[1]);
                string strNagivation = null;
                parameters.TryGetValue("navType".ToLower(), out strNagivation);
                if (!string.IsNullOrEmpty(strNagivation))
                {
                    if (strNagivation.Equals("import", StringComparison.InvariantCultureIgnoreCase))
                    {                        
                        return NavType.Import;
                    }
                    else if (strNagivation.Equals("optimization", StringComparison.InvariantCultureIgnoreCase))
                    {
                        return NavType.Optimization;
                    }
                    else if (strNagivation.Equals("scenario", StringComparison.InvariantCultureIgnoreCase))
                    {
                        return NavType.Scenario;
                    }
                }
            }
            return NavType.NoDefined;
        }
        #endregion

        #region Application_Startup
        private void Application_Startup(object sender, StartupEventArgs e)
        {
            if (e.InitParams.ContainsKey("CustomPageName"))
                CustomPageName = e.InitParams["CustomPageName"];

            if (e.InitParams.ContainsKey("LoginUserId"))
                LoginUserId = e.InitParams["LoginUserId"];

            if (e.InitParams.ContainsKey("UserName"))
                LoginUserName = e.InitParams["UserName"];

            if (e.InitParams.ContainsKey("Email"))
                LoginEmail = e.InitParams["Email"];


            this.RootVisual = new MainDashBoard();

            // Commented by Dhilip for Navigation with Page refreshing logic
            /*
            NavType navType = NavigationCheck();
            if (navType == NavType.Import)
                this.RootVisual = ServiceLocator.Get<Import>();
            else if (navType == NavType.Optimization)
                this.RootVisual = ServiceLocator.Get<Optimization>();
            else if (navType == NavType.Scenario)
                this.RootVisual = ServiceLocator.Get<Scanario>();
            else
                this.RootVisual = ServiceLocator.Get<MainPage>();*/
        }
        #endregion

        #region Application_Exit
        private void Application_Exit(object sender, EventArgs e)
        {

        }
        #endregion
        
        #region Application_UnhandledException
        private void Application_UnhandledException(object sender, ApplicationUnhandledExceptionEventArgs e)
        {
            // If the app is running outside of the debugger then report the exception using
            // the browser's exception mechanism. On IE this will display it a yellow alert 
            // icon in the status bar and Firefox will display a script error.
            if (!System.Diagnostics.Debugger.IsAttached)
            {

                // NOTE: This will allow the application to continue running after an exception has been thrown
                // but not handled. 
                // For production applications this error handling should be replaced with something that will 
                // report the error to the website and stop the application.
                e.Handled = true;
                Deployment.Current.Dispatcher.BeginInvoke(delegate { ReportErrorToDOM(e); });
            }
        }
        #endregion

        #region ReportErrorToDOM
        private void ReportErrorToDOM(ApplicationUnhandledExceptionEventArgs e)
        {
            try
            {
                string errorMsg = e.ExceptionObject.Message + e.ExceptionObject.StackTrace;
                errorMsg = errorMsg.Replace('"', '\'').Replace("\r\n", @"\n");

                System.Windows.Browser.HtmlPage.Window.Eval("throw new Error(\"Unhandled Error in Silverlight Application " + errorMsg + "\");");
            }
            catch (Exception)
            {
            }
        }
        #endregion
    }
}
